﻿$$.Touch = new function (mouseable) {
	var me = this;
	function start(evt) { this.TouchTime = evt.timeStamp; }
	function move(evt) { this.TouchTime = 0; }
	function cancel(evt) { this.TouchTime = 0; }

	me.OnTap = function (node, callback, one) {
		if (!node || !callback) return;
		var callb = callback;
		if (one === true) callb = function (evt) {
			jQuery.event.remove(node, "touchstart.Tap");
			jQuery.event.remove(node, "touchmove.Tap");
			jQuery.event.remove(node, "touchend.Tap");
			jQuery.event.remove(node, "touchcancel.Tap");
			jQuery.event.remove(node, "click.Tap");
			callb.call(node, evt);
		};
		jQuery.event.add(node, "touchstart.Tap", start);
		jQuery.event.add(node, "touchmove.Tap", move);
		jQuery.event.add(node, "touchcancel.Tap", cancel);
		jQuery.event.add(node, "click.Tap", callb);
		jQuery.event.add(node, "touchend.Tap", function (evt) {
			if (this.TouchTime === 0) return;
			var time = evt.timeStamp - this.TouchTime;
			this.TouchTime = 0;
			if (time < 1 || time > 500) return;
			//evt.stopImmediatePropagation();
			//evt.preventDefault();
			//evt.returnValue = false;
			callb.call(this, evt);
			return false;
		});
	};
	me.OffTap = function (node) {
		jQuery.event.remove(node, "touchstart.Tap");
		jQuery.event.remove(node, "touchmove.Tap");
		jQuery.event.remove(node, "touchcancel.Tap");
		jQuery.event.remove(node, "touchend.Tap");
		jQuery.event.remove(node, "click.Tap");
	};

	jQuery.fn.extend({
		onClick: function (callback) {
			for (var i = 0; i < this.length; i++) { me.OnTap(this[i], callback); }
			return this;
		},
		oneClick: function (callback) {
			for (var i = 0; i < this.length; i++) { me.OnTap(this[i], callback, one); }
			return this;
		},
		offClick: function () {
			for (var i = 0; i < this.length; i++) { me.OffTap(this[i]); }
			return this;
		}
	});
};